import Vue from 'vue';
import VueRouter from 'vue-router';
// eslint-disable-next-line
import Store from '@/store';

Vue.use(VueRouter);

// 路由规则
const routes = [
  {
    path: '/',
    name: 'Home',
    meta: { requiresAuth: true },
    component: () => import(/* webpackChunkName: "home" */'@/views/home/index.vue'),
    children: [
      {
        path: '/role',
        name: 'role',
        component: () => import(/* webpackChunkName: "role" */'@/views/role/index.vue'),
      },
      {
        path: ':id/allocMenu',
        name: 'allocmenu',
        component: () => import(/* webpackChunkName: "allocMenu" */'@/views/role/AllocMenu.vue'),
        props: true,
      },
      {
        path: ':id/allocResource',
        name: 'allocresource',
        component: () => import(/* webpackChunkName: "allocresource" */'@/views/role/AllocResource.vue'),
        props: true,
      },
      {
        path: '/menu',
        name: 'menu',
        component: () => import(/* webpackChunkName: "menu" */'@/views/menu/index.vue'),
      },
      {
        path: '/addmenu',
        name: 'addmenu',
        component: () => import(/* webpackChunkName: "addmenu" */'@/views/menu/MenuEdit.vue'),
      },
      {
        path: '/editmenu/:id',
        name: 'editmenu',
        component: () => import(/* webpackChunkName: "addmenu" */'@/views/menu/MenuEdit.vue'),
        props: true,
      },
      {
        path: '/resource',
        name: 'resource',
        component: () => import(/* webpackChunkName: "resource" */'@/views/resource/index.vue'),
      },
      {
        path: '/user',
        name: 'user',
        component: () => import(/* webpackChunkName: "user" */'@/views/user/index.vue'),
      },
      {
        path: '/lesson',
        name: 'lesson',
        component: () => import(/* webpackChunkName: "lesson" */'@/views/lesson/index.vue'),
      },
      {
        path: '/lesson/addlesson',
        name: 'addlesson',
        component: () => import(/* webpackChunkName: "lesson" */'@/views/lesson/CourseEdit.vue'),
      },
      {
        path: '/lesson/:id/editlesson',
        name: 'editlesson',
        props: true,
        component: () => import(/* webpackChunkName: "lesson" */'@/views/lesson/CourseEdit.vue'),
      },
      {
        path: '/lesson/:id/section',
        name: 'section',
        props: true,
        component: () => import(/* webpackChunkName: "lesson" */'@/views/lesson/SectionEdit.vue'),
      },
    ],
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import(/* webpackChunkName: "login" */'@/views/login/index.vue'),
  },
];

const router = new VueRouter({
  routes,
});

router.beforeEach((to, from, next) => {
  if (to.matched.some((record) => record.meta.requiresAuth)) {
    if (!Store.state.user) {
      next({
        path: '/login',
        query: { redirect: to.fullPath },
      });
    } else {
      next();
    }
  } else {
    next(); // 确保一定要调用 next()
  }
});
export default router;
